import React from 'react'
import {connect} from 'react-redux'
import menuRoute from 'routes/menuRoute'
import SlideFrame from 'components/slide-frame'
import SearchArea from 'components/search-area'
import backlashService from './pay-backlash.service'
import moment from 'moment'
import { Table, Popover } from 'antd'
import toBacklash from './to-backlash';
import {messages, queryCurrencyPrecision} from 'share/common'

class PayMyBacklash extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      setOfBooksId: null,
      searchForm: [
        {type: 'input', id: 'billcode', label: messages('pay.key20')/*付款流水号*/},
        {type: 'input', id: 'documentNumber', label: messages('pay.key104')/*单据编号*/},
        {
          type: 'select',
          id: 'documentTypeId',
          label: messages('pay.key105')/*单据类型*/,
          options: [{
            value: 'PAYMENT_REQUISITION',
            label: messages('pay.key167')/*借款单*/
          },{
            value: 'EXP_REPORT',
            label: messages('pay.key168')/*报销单*/
          }],
        },
        {
          type: 'items', id: 'partner', items: [
            {
              type: 'value_list',
              id: 'partnerCategory',
              label: messages('pay.key18')/*类型*/,
              valueListCode: 2107,
              options: [],
              event: 'PARTNER'
            },
            {
              type: 'list',
              id: 'partnerId',
              label: messages('pay.key19')/*收款方*/,
              listType: 'select_payee',
              single: true,
              disabled: true,
              labelKey: 'fullName',
              valueKey: "id"
            },
          ]
        },
        {
          type: 'items', id: 'dateRange', items: [
            {type: 'date', id: 'payDateFrom', label: messages('pay.key169')/*付款日期从*/},
            {type: 'date', id: 'payDateTo', label: messages('pay.key170')/*付款日期到*/}
          ]
        },
        {
          type: 'items', id: 'amountRange', items: [
            {type: 'inputNumber', id: 'amountFrom', label: messages('pay.key171')/*付款金额从*/},
            {type: 'inputNumber', id: 'amountTo', label: messages('pay.key172')/*付款金额到*/}
          ]
        },
        {
          type: 'list',
          listType: "select_authorization_user",
          options: [],
          id: 'applicant',
          label: messages('pay.key15')/*申请人*/,
          labelKey: "userName",
          valueKey: "userId",
          single: true
        }, //申请人
      ],
      canBacklashSearchParams: {},
      columns: [
        {
          title: messages('pay.key20')/*付款流水号*/, dataIndex: 'billcode', width: 150, align: "center",
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key104')/*单据编号*/, dataIndex: 'documentNumber', width: 150,
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key105')/*单据类型*/, dataIndex: 'documentCategoryName',
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key15')/*申请人*/, dataIndex: 'employeeName', width: 150,
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key107')/*付款金额*/, dataIndex: 'amount',
          render: (desc ,record) => <span><Popover
            content={this.filterMoney(desc, queryCurrencyPrecision(record.currency), true)}>{this.filterMoney(desc, queryCurrencyPrecision(record.currency), true)}</Popover></span>
        },
        {
          title: messages('pay.key82')/*币种*/, dataIndex: 'currency',
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key173')/*收款方名称*/, dataIndex: 'partnerName',
          render: (value, record) => {
            return (
              <div>
                {record.partnerCategoryName}
                <span className="ant-divider"/>
                {value}
              </div>
            )
          }
        },
        {
          title: messages('pay.key101')/*付款日期*/, dataIndex: 'payDate',
          render: desc => <span><Popover
            content={moment(desc).format('YYYY-MM-DD')}>{desc ? moment(desc).format('YYYY-MM-DD') : "-"}</Popover></span>
        },
        {
          title: messages('common.operation')/*操作*/, render: (value, record) => {
            record.flag = false;
            return (
              <a onClick={() => {
                this.goBacklash(record)
              }}>{messages('pay.key174')/*发起反冲*/}</a>
            )
          }
        }
      ],
      data: [],
      canBacklashPage: 0,
      canBacklashPageSize: 10,
      searchParams: {},
      canBacklashPagination: {
        total: 0
      },
      canBacklashData: [],
      goBacklash: null,
      openWindowFlag: false  //发起反冲窗口
    };
  }

  //去反冲页面
  goBacklash = (record) => {
    backlashService.getReadyByDetailId(record.id).then(
      res => {
        if (res.status === 200) {
          this.setState({openWindowFlag: true, goBacklash: res.data})
        }
      }
    )
  };

  //反冲窗口关闭
  cancelWindow = () => {
    this.setState({openWindowFlag: false});
  };

  //反冲窗口完全关闭后回掉
  restFormFunc = () => {
    this.setState({openWindowFlag: false}, () => {
      this.getCanBacklashList();
    });
  };

  //可反冲列表搜索
  canBacklashHandle = (values) => {
    values.payDateFrom && (values.payDateFrom = values.payDateFrom.format('YYYY-MM-DD'));
    values.payDateTo && (values.payDateTo = values.payDateTo.format('YYYY-MM-DD'));
    if (JSON.stringify(values.partnerId) !== '[]' && values.partnerId) {
      (values.partnerId = values.partnerId[0].id)
    }
    this.setState({canBacklashSearchParams: values, canBacklashPage: 0}, () => {
      this.getCanBacklashList()
    })
  };


  componentWillMount() {
    this.getCanBacklashList(this.state.nowStatus);
  }

  //可反冲点击页码
  canBacklashChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({canBacklashPage: page - 1}, () => {
        this.getCanBacklashList()
      })
    }
  };

  //获取可反冲列表
  getCanBacklashList = (resolve, reject) => {
    const {canBacklashPage, canBacklashPageSize, canBacklashSearchParams} = this.state;
    this.setState({loading1: true});
    let params = {...canBacklashSearchParams, page: canBacklashPage, size: canBacklashPageSize, backlashStatus: 'N'};
    backlashService.getCanBacklashList(params).then((res) => {
      if (res.status === 200) {
        this.setState({
          canBacklashData: res.data || [],
          loading1: false,
          canBacklashPagination: {
            total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0,
            current: canBacklashPage + 1,
            pageSize: canBacklashPageSize,
            onChange: this.canBacklashChangePaper,
            pageSizeOptions: ['10', '20', '30', '40'],
            showSizeChanger: true,
            onShowSizeChange: this.onChangePageSize,
            showQuickJumper: true,
            showTotal: (total, range) => {messages('pay.key175',{arg1:range[0],arg2:range[1],arg3:total})/*显示 {arg1}-{arg2} 共 {arg3} 条*/}
          }
        });
        resolve && resolve()
      }
    }).catch(() => {
      this.setState({loading1: false});
      reject && reject()
    })
  };

  //每页多少条
  onChangePageSize = (page, pageSize) => {
    if (page - 1 !== this.state.canBacklashPage || pageSize !== this.state.canBacklashPageSize) {
      this.setState({canBacklashPage: page - 1, canBacklashPageSize: pageSize}, () => {
        this.getCanBacklashList();
      })
    }
  };

  clear = () => {
    this.setState({canBacklashSearchParams: {}}, () => {
      this.searchEventHandle("PARTNER", "");
    })
  };

  searchEventHandle = (event, value) => {
    if (event === "PARTNER") {
      let searchForm = this.state.searchForm;
      value = value ? value : "";
      if (value === "EMPLOYEE") {
        let item = searchForm[3];
        item.items[1].disabled = false;
        item.items[1].listType = 'select_payee';
        item.items[1].labelKey = 'fullName';
        searchForm[3] = item;
        this.formRef.setValues({partnerId: undefined});
        this.setState({searchForm: searchForm})
      }
      if (value === "VENDER") {
        let item = searchForm[3];
        item.items[1].disabled = false;
        item.items[1].listType = 'vendor_type';
        item.items[1].labelKey = 'name';
        searchForm[3] = item;
        this.formRef.setValues({partnerId: undefined});
        this.setState({searchForm: searchForm})
      }
      if (value === "") {
        let item = searchForm[3];
        item.items[1].disabled = true;
        searchForm[3] = item;
        this.formRef.setValues({partnerId: undefined});
        this.setState({searchForm: searchForm})
      }
    }
  };

  render() {
    const {goBacklash, openWindowFlag, loading1, searchForm, columns, canBacklashData, canBacklashPagination} = this.state;
    return (
      <div className="pay-my-backlash">
        <SearchArea searchForm={searchForm}
                    submitHandle={this.canBacklashHandle}
                    clearHandle={this.clear}
                    eventHandle={this.searchEventHandle}
                    wrappedComponentRef={(inst) => this.formRef = inst}/>
        <div className="table-header"/>
        <Table rowKey={record => record.id}
               columns={columns}
               dataSource={canBacklashData}
               pagination={canBacklashPagination}
               loading={loading1}
               bordered
               size="middle"/>
        <SlideFrame title={messages('pay.key176')/*反冲信息详情*/}
                    show={openWindowFlag}
                    content={toBacklash}
                    params={{record: goBacklash, flag: openWindowFlag, isCan: true}}
                    onClose={this.cancelWindow}
                    afterClose={this.restFormFunc}/>
      </div>
    );
  }
}


PayMyBacklash.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  }
}


export default connect(mapStateToProps, null, null, {withRef: true})(PayMyBacklash);


